import { constantRoutes } from '@/router'

// 判断当前用户角色是否有权限访问该路由
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true // 没写roles默认都能访问
  }
}

// 递归过滤静态路由表
export function filterRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const permission = {
  namespaced: true,
  state: {
    routes: constantRoutes,
    addRoutes: constantRoutes,
    defaultRoutes: constantRoutes,
    topbarRouters: constantRoutes,
    sidebarRouters: constantRoutes
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = routes
      state.sidebarRouters = routes
      state.topbarRouters = routes
    }
  },
  actions: {
    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        const accessedRoutes = filterRoutes(constantRoutes, roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
}

export default permission
